/*
 * Copyright 2014 Christian Hildebrandt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.sisoft.timera.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.sisoft.timera.beans.LoginBean;
import de.sisoft.timera.entity.Role;

/**
 * Filter checks if LoginBean has loginIn property set to true. If it is not set
 * then request is being redirected to the login.xhml page. Also check on Role
 * of user.
 *
 * @author Christian Hildebrandt
 *
 */
public class SecurityFilter implements Filter {

    /**
     * Checks if user is logged in. If not it redirects to the login.xhtml page.
     */
    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
	    throws IOException, ServletException {
	// Get the loginBean from session attribute
	final LoginBean loginBean = (LoginBean) ((HttpServletRequest) request).getSession().getAttribute("loginBean");

	// For the first application request there is no loginBean in the
	// session so user needs to log in
	// For other requests loginBean is present but we need to check if user
	// has logged in successfully.
	// For logged in users we need to check the security level and requested
	// access to page.
	if ((loginBean == null) || !loginBean.isLoggedIn()) {
	    final String contextPath = ((HttpServletRequest) request).getContextPath();
	    ((HttpServletResponse) response).sendRedirect(contextPath + "/login.xhtml");
	} else {
	    // User is logged in and session is valid, so we just have to check
	    // if it is an admin
	    final String reqestURI = ((HttpServletRequest) request).getRequestURI();
	    if ((reqestURI.indexOf("/Admin") >= 0) && !loginBean.getLogggedInUser().hasRole(Role.ADMIN)) {
		((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
	    }
	}
	chain.doFilter(request, response);

    }

    @Override
    public void init(final FilterConfig config) throws ServletException {
	// Nothing to do here!
    }

    @Override
    public void destroy() {
	// Nothing to do here!
    }

}
